package org.xiaojinlong.playground;

import java.util.*;

public class Joiner {
    interface ElementJoiner {
        /**
         * 将ts里的元素以delimiter为分隔符连接起来。如
         * join(new Integer[]{1, 2, 3}, " | ") 会得到"1 | 2 | 3"
         *
         * @param ts        要连接的数组
         * @param delimiter 分隔符
         */
        public <T> String join(T[] ts, String delimiter);

        /**
         * 将ts里的元素以delimiter为分隔符连接起来。
         * 在连接的结果中元素出现的顺序要按照集合自身的迭代器顺序。
         *
         * @see #join(T[], java.lang.String)
         */
        public <T> String join(Collection<T> ts, String delimiter);
    }

    class ElementJoinerImpl implements ElementJoiner {
        @Override
        public <T> String join(T[] ts, String delimiter) {
            if (ts != null) {
                StringBuilder buf = new StringBuilder();
                for (T t : ts)
                    buf.append(t.toString()).append(delimiter);
                return buf.substring(0, buf.length() - delimiter.length());
            } else {
                return delimiter;
            }
        }

        @Override
        public <T> String join(Collection<T> ts, String delimiter) {
            if (ts != null) {
                StringBuilder buf = new StringBuilder();
                for (T t : ts)
                    buf.append(t.toString()).append(delimiter);
                return buf.substring(0, buf.length() - delimiter.length());
            } else {
                return delimiter;
            }
        }
    }

    public static void main(String[] args) {

    }
}




